import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sensors/sensors.dart';
import 'dart:ui' as ui;
import 'package:flutter_screenutil/flutter_screenutil.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

const String pic = 'http://pic75.nipic.com/file/20150821/9448607_145742365000_2.jpg';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ImageClipper clipper;

  @override
  void initState() {
    super.initState();
    gyroscopeEvents.listen((GyroscopeEvent event) {
//      print(event);
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 1080, height: 1920, allowFontScaling: false);

    return Scaffold(
      appBar: AppBar(
        title: Text('ImageClipperWithGyroscope'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            SizedBox(
              child: Container(
                  color: Colors.grey,
                  child: Image.network(
                    pic,
                    fit: BoxFit.fill,
                  )),
            ),
            SizedBox(
              height: 50,
            ),
            Container(
                color: Colors.green,
                child: CustomPaint(
                  painter: clipper,
                  size: Size(double.infinity, 620.h),
                )),
            RaisedButton(child: Text('Clip'), onPressed: () => clip())
          ],
        ),
      ),
    );
  }

  Future<ui.Image> _loadImage() async {
    ImageStream imageStream = NetworkImage(pic).resolve(ImageConfiguration());
    Completer<ui.Image> completer = Completer<ui.Image>();
    void imageListener(ImageInfo info, bool synchronousCall) {
      ui.Image image = info.image;
      completer.complete(image);
      imageStream.removeListener(ImageStreamListener(imageListener));
    }

    imageStream.addListener(ImageStreamListener(imageListener));
    return completer.future;
  }

  clip() async {
    ui.Image uiImage;
    _loadImage().then((image) {
      uiImage = image;
    }).whenComplete(() {
      clipper = ImageClipper(uiImage);
      setState(() {});
    });
  }
}

/// 图片裁剪
class ImageClipper extends CustomPainter {
  final ui.Image image;

  ImageClipper(this.image);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    canvas.drawImageRect(image, Rect.fromLTRB(0, 0, image.width * 0.5, image.height * 0.5),
        Rect.fromLTWH(0, 0, size.width, size.height), paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
